/**
 *@功能说明 :
 * 2015 2015-6-3 上午11:08:47
 * code by zhugefubin
 */
package xyz.litecoder.demos;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.ScrollView;

/**
 * @author zhugefubin
 * 
 */
public class ZScrolImagelView extends ScrollView {

	private ZImageView child;

	@SuppressLint("NewApi")
	public ZScrolImagelView(Context context, AttributeSet attrs,
			int defStyleAttr, int defStyleRes) {
		super(context, attrs, defStyleAttr, defStyleRes);
		initThis();
	}

	public ZScrolImagelView(Context context, AttributeSet attrs,
			int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		initThis();
	}

	public ZScrolImagelView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initThis();
	}

	public ZScrolImagelView(Context context) {
		super(context);
		initThis();
	}

	/**
	 * @return child
	 * @字段类型 ZImageView
	 */
	public ZImageView getChild() {
		return child;
	}

	/**
	 * @see android.widget.ScrollView#onInterceptTouchEvent(android.view.MotionEvent)
	 * @param ev
	 * @return
	 */
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		return getChild().isScollMode();
	}

	/**
	 * @说明
	 */
	private void initThis() {
		this.child = new ZImageView(getContext());
		addView(child);
	}

	/**
	 * @return isScollMode
	 * @字段类型 boolean
	 */
	public boolean isScollMode() {
		return getChild().isScollMode();
	}

	/**
	 * @return handWritingLayer
	 * @字段类型 Bitmap
	 */
	public Bitmap getHandWritingLayer() {

		return getChild().cachebBitmap;
	}

	/**
	 * @param handWritingLayer
	 *            要设置的 handWritingLayer
	 * @字段类型 Bitmap
	 */
	public void setHandWritingLayer(Bitmap handWritingLayer) {
		getChild().setCachebBitmap(handWritingLayer);
	}

	public void setImageBitmap(Bitmap bm) {
		getChild().setImageBitmap(bm);
	}

	public void setImageResource(int resId) {
		getChild().setImageResource(resId);
	}

	public void setImageDrawable(Drawable drawable) {
		getChild().setImageDrawable(drawable);
	}

	/**
	 * @param color
	 * @说明
	 */
	public void setColor(int color) {
		getChild().setColor(color);
	}

	public int getColor() {

		return getChild().getColor();
	}

	/**
	 * @return strokeWidth
	 * @字段类型 float
	 */
	public float getStrokeWidth() {

		return getChild().getStrokeWidth();
	}

	/**
	 * @param strokeWidth
	 *            要设置的 strokeWidth
	 * @字段类型 float
	 */
	public void setStrokeWidth(float strokeWidth) {
		getChild().setStrokeWidth(strokeWidth);
	}

	/**
	 * @说明 擦除模式
	 */
	public void clearMode() {
		getChild().clearMode();
	}

	/**
	 * @绘画模式
	 */
	public void drawMode() {
		getChild().drawMode();
	}

	/**
	 * @绘画模式
	 */
	public void scrollMode() {
		getChild().scrollMode();
	}

	public void saveToFile(String filename) throws FileNotFoundException {
		getChild().saveToFile(filename);
	}

	class ZImageView extends ImageView {
		private Paint mPaint;// 绘图画笔
		private Bitmap cachebBitmap;// 手写缓存图层
		private Canvas mCanvas;// 手写缓存画布
		private Path mPath;// 手写路径
		private Paint cachebBitmapPaint;// 缓存画笔
		private float strokeWidth = 3;// 默认线条宽度
		private ExecutorService taskPool;
		private Bitmap image;// 当前imageView显示的图片
		private boolean isScollMode = false;
		private int width = 1;
		private int height = 1;
		/**
		 * @param cachebBitmap 要设置的 cachebBitmap
		 * @字段类型 Bitmap 
		 */
		public void setCachebBitmap(Bitmap cachebBitmap) {
			this.cachebBitmap = cachebBitmap;
			mCanvas = new Canvas(this.cachebBitmap);
			invalidate();
		}

		/**
		 * @return isScollMode
		 * @字段类型 boolean
		 */
		public boolean isScollMode() {
			return isScollMode;
		}

		@SuppressLint("NewApi")
		public ZImageView(Context context, AttributeSet attrs,
				int defStyleAttr, int defStyleRes) {
			super(context, attrs, defStyleAttr, defStyleRes);
			init();
		}

		public ZImageView(Context context, AttributeSet attrs, int defStyleAttr) {

			super(context, attrs, defStyleAttr);
			init();
		}

		public ZImageView(Context context, AttributeSet attrs) {

			super(context, attrs);
			init();
		}

		public ZImageView(Context context) {
			super(context);
			init();
		}

		/**
		 * @return handWritingLayer
		 * @字段类型 Bitmap
		 */
		public Bitmap getHandWritingLayer() {

			return cachebBitmap;
		}

		/**
		 * @param handWritingLayer
		 *            要设置的 handWritingLayer
		 * @字段类型 Bitmap
		 */
		public void setHandWritingLayer(Bitmap handWritingLayer) {
			this.cachebBitmap = handWritingLayer;
			invalidate();
		}

		public void init() {
			mPath = new Path();
			cachebBitmapPaint = new Paint(Paint.DITHER_FLAG);
			mPaint = new Paint();
			mPaint.setAntiAlias(true);
			mPaint.setDither(true);
			mPaint.setColor(0xFFFF0000);
			mPaint.setStyle(Paint.Style.STROKE);
			mPaint.setStrokeJoin(Paint.Join.ROUND);
			mPaint.setStrokeCap(Paint.Cap.ROUND);
			mPaint.setStrokeWidth(strokeWidth);
			setScaleType(ScaleType.FIT_CENTER);
			taskPool = Executors.newFixedThreadPool(3);
		}

		@Override
		public void setImageBitmap(Bitmap bm) {
			super.setImageBitmap(bm);
			this.image = bm;
		}

		@Override
		public void setImageResource(int resId) {
			super.setImageResource(resId);
			this.image = BitmapFactory.decodeResource(getResources(), resId);
		}

		@Override
		public void setImageDrawable(Drawable drawable) {
			super.setImageDrawable(drawable);
			BitmapDrawable bd = (BitmapDrawable) drawable;
			this.image = bd.getBitmap();
		}

		/**
		 * @param color
		 * @说明
		 */
		public void setColor(int color) {
			mPaint.setColor(color);
		}

		public int getColor() {
			return mPaint.getColor();
		}

		/**
		 * @return strokeWidth
		 * @字段类型 float
		 */
		public float getStrokeWidth() {

			return strokeWidth;
		}

		/**
		 * @param strokeWidth
		 *            要设置的 strokeWidth
		 * @字段类型 float
		 */
		public void setStrokeWidth(float strokeWidth) {
			this.strokeWidth = strokeWidth;
		}

		/**
		 * @说明 擦除模式
		 */
		public void clearMode() {
			mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
			mPaint.setStrokeWidth(30);
			// mPaint.setColor(Color.TRANSPARENT);
			isScollMode = false;
		}

		/**
		 * @绘画模式
		 */
		public void drawMode() {
			mPaint.setXfermode(null);
			mPaint.setAlpha(0xFF);
			mPaint.setStrokeWidth(strokeWidth);
			mPaint.setColor(Color.RED);
			isScollMode = false;
		}

		/**
		 * @绘画模式
		 */
		public void scrollMode() {
			isScollMode = true;
		}

		// /**
		// * @说明
		// */
		// private void initCachebBitmap() {
		// if (cachebBitmap == null) {
		//
		// int w = this.image.getWidth();
		// int h = this.image.getHeight();
		// cachebBitmap = Bitmap.createBitmap(w, h,
		// Bitmap.Config.ARGB_8888);
		// mCanvas = new Canvas(cachebBitmap);
		// try {
		// mCanvas.drawBitmap(BitmapFactory
		// .decodeFile("/sdcard/temp/drawTemp.png"), 0, 0,
		// null);
		// } catch (Exception e) {
		// Log.d(VIEW_LOG_TAG, "没发现临时文件");
		// }
		// }
		// }
		/**
		 * @see android.view.View#onSizeChanged(int, int, int, int)
		 * @param w
		 * @param h
		 * @param oldw
		 * @param oldh
		 */
		@Override
		protected void onSizeChanged(int w, int h, int oldw, int oldh) {
			super.onSizeChanged(w, h, oldw, oldh);
			this.width = w;
			this.height = h;
			cachebBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
			mCanvas = new Canvas(cachebBitmap);
//			try {
//				mCanvas.drawBitmap(
//						BitmapFactory.decodeFile("/sdcard/temp/drawTemp.png"),
//						0, 0, null);
//			} catch (Exception e) {
//				Log.d(VIEW_LOG_TAG, "没发现临时文件");
//			}
		}

		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);
			canvas.drawPath(mPath, mPaint);
			cachebBitmapPaint.setColor(mPaint.getColor());
			canvas.drawBitmap(cachebBitmap, 0, 0, cachebBitmapPaint);
			taskPool.execute(new SaveBitmapThread());
		}

		class SaveBitmapThread extends Thread {
			@Override
			public void run() {
				mCanvas.save(Canvas.ALL_SAVE_FLAG);
				mCanvas.restore();
				Log.d(VIEW_LOG_TAG, "mCanvas.save()");
			}
		}

		// private static final float TOUCH_TOLERANCE = 4;

		private void touch_start(float x, float y) {
			mPath.reset();
			mPath.moveTo(x, y);
			mCanvas.drawPath(mPath, mPaint);
		}

		private void touch_move(float x, float y) {
			// float dx = Math.abs(x - mX);
			// float dy = Math.abs(y - mY);
			// if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
			// mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
			// mX = x;
			// mY = y;
			// }
			mPath.lineTo(x, y);
			mCanvas.drawPath(mPath, mPaint);
		}

		private void touch_up(float x, float y) {
			mPath.lineTo(x, y);
			// commit the path to our offscreen
			mCanvas.drawPath(mPath, mPaint);
			// kill this so we don't double draw
			mPath.reset();
		}

		@SuppressLint("ClickableViewAccessibility")
		@Override
		public boolean onTouchEvent(MotionEvent event) {
			System.out.println("x:" + event.getX() + "\ty:" + event.getY());
			if (isScollMode) {
				return false;
			} else {
				float x = event.getX();
				float y = event.getY();
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					touch_start(x, y);
					invalidate();
					return true;
				case MotionEvent.ACTION_MOVE:
					touch_move(x, y);
					invalidate();
					return true;
				case MotionEvent.ACTION_UP:
					touch_up(x, y);
					invalidate();
					return true;
				}
			}
			return true;
		}

		public void saveToFile(String filename) throws FileNotFoundException {
			File f = new File(filename);
			// if (f.exists())
			// throw new RuntimeException("文件：" + filename + " 已存在！");

			FileOutputStream fos = new FileOutputStream(new File(filename));
			// 将 bitmap 压缩成其他格式的图片数据
			cachebBitmap.compress(CompressFormat.PNG, 100, fos);
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
